package com.example.assignment5.controll;


import com.example.assignment5.exception.R;
import com.example.assignment5.commodity;
import com.example.assignment5.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @GetMapping
    private R getAll(){
        return R.success(commodityService.getAll());
    }

    @GetMapping("/{id}")
    private R getById(@PathVariable Long id){
        return R.success(commodityService.getById(id));
    }

    @PostMapping
    private R add(@RequestBody commodity commodity){
        commodityService.add(commodity);
        return R.success("添加成功");
    }

    @PutMapping("/{id}")
    private R update(@PathVariable Long id,@RequestBody commodity commodity){
        if(id==commodity.getId()){
            commodityService.updateById(commodity);
            return R.success("修改成功");
        }else {
            return R.error("id错误");
        }
    }

    @DeleteMapping("/{id}")
    private R deleteById(@PathVariable Long id){
        commodityService.deleteById(id);
        return R.success("删除成功");
    }

    @GetMapping("/{name}")
    private R getByName(@PathVariable String name){
        return R.success(commodityService.getByName(name));
    }

    @GetMapping("/contain/{name}")
    private R getByNameContaining(@PathVariable String name){
        return R.success(commodityService.getByNameContaining(name));
    }
}
